package 笔记.设计模式.代理模式.spring.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import 笔记.设计模式.代理模式.spring.MyAspect;
import 笔记.设计模式.代理模式.spring.User;
import 笔记.设计模式.代理模式.spring.UserImpl;

import java.lang.reflect.Method;

/**
 * @author chenhailong
 * @ClassName: CjLibProxy
 * @Description: 代理的目标对象可以实现接口，也可以不实现接口；主要引用的是第三方jar包，通过字节码处理框架ASM转换字节码并生成新的类。
 * @date 2021/8/6 11:13
 * @Version 1.0
 */
public class CgLibProxy implements MethodInterceptor {


    private Object tarage;

    private Object getTarage(Object o) {
        this.tarage = o;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(o.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        MyAspect myAspect = new MyAspect();
        myAspect.myBefore();
        Object invoke = method.invoke(tarage, objects);
        myAspect.myAfter();

        return invoke;
    }

    public static void main(String[] args) {
        CgLibProxy cg = new CgLibProxy();
        User user = (User) cg.getTarage(new UserImpl());
        user.add();
        user.del();

    }
}
